package com.cskaoyan.service.impl;

import com.cskaoyan.bean.bo.CollectAddOrDeleteBO;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.GoodsListVO;
import com.cskaoyan.mapper.MarketCollectMapper;
import com.cskaoyan.mapper.MarketGoodsMapper;
import com.cskaoyan.service.CollectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 微信-个人中心-收藏
 * 创建日期: 2022/04/09 19:52
 *
 * @author ChengWenqi
 */

@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    MarketCollectMapper collectMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Transactional
    @Override
    public GoodsListVO queryCollectList(byte type, int page, int limit, Integer userId) {
        // 开启分页
        PageHelper.startPage(page, limit);
        // 根据用户id，在 market_collect 表中查找所有未删除、type=0 的 value_id（即goodsID）
        MarketCollectExample example = new MarketCollectExample();
        // 按update_time降序
        example.setOrderByClause("update_time desc");
        MarketCollectExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false).andUserIdEqualTo(userId).andTypeEqualTo(type);
        List<MarketCollect> collectList = collectMapper.selectByExample(example);

        // 获取分页信息
        PageInfo<MarketCollect> pageInfo = new PageInfo<>(collectList);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();
        List<MarketGoods> list = new ArrayList<>();
        // 如果没有收藏，返回空的list
        if (!collectList.isEmpty()) {
            // 对每一个goodsId，在 market_goods 表中查找信息，加入List
            for (MarketCollect collect : collectList) {
                Integer valueId = collect.getValueId();
                MarketGoods goods = goodsMapper.selectByPrimaryKey(valueId);
                if (!goods.getDeleted()) {
                    goods.setValueId(goods.getId());
                    list.add(goods);
                }
            }
        }
        return new GoodsListVO((int) total, pages, limit, page, list);
    }

    @Override
    public void collectAddOrDelete(CollectAddOrDeleteBO collectAddOrDeleteBO, MarketUser user) {
        @NotNull Byte type = collectAddOrDeleteBO.getType();
        @NotNull Integer valueId = collectAddOrDeleteBO.getValueId();
        Integer userId = user.getId();
        // 根据以上三个信息，查询 market_collect 表
        MarketCollectExample example = new MarketCollectExample();
        MarketCollectExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(type).andValueIdEqualTo(valueId).andUserIdEqualTo(userId);
        List<MarketCollect> collects = collectMapper.selectByExample(example);
        // 情况一：该商品以前收藏过，后来可能又取消了，可能还在收藏中
        // 如果查到一条记录，反转 deleted 的值，并更新 update_time
        if (collects.size() == 1) {
            MarketCollect collect = collects.get(0);
            if (collect.getDeleted()) {
                collect.setDeleted(false);
            } else {
                collect.setDeleted(true);
            }
            collect.setUpdateTime(new Date());
            collectMapper.updateByExampleSelective(collect, example);
        }
        // 情况二：该商品从未收藏过，添加到 market_collect 表中
        if (collects.isEmpty()) {
            MarketCollect collect = new MarketCollect(null, userId, valueId, type, new Date(), new Date(), false);
            collectMapper.insert(collect);
        }
    }
}
